<?php
class View
{
    # Wrapper template
    protected $_master_template;

    protected $_master_template_file = FALSE;
    protected $_use_master_template = true;

    # Sub template
    protected $_template;
    protected $_action;
    protected $_controller;

    # Khởi tạo View, yêu cầu tên controller (chỉ phần tên) và action
    public function __construct($controller, $action)
    {
        $this->_template = new SmTemplate();
        $this->_master_template = new SmTemplate();
        $this->_controller = strtolower($controller);
        $this->_action = $action;
    }

    public function setMasterTemplate($file)
    {
        $this->_master_template_file = $file;
    }

    public function useMasterTemplate($b = true)
    {
        $this->_use_master_template = $b;
    }

    public function ignoreMasterTemplate()
    {
        $this->useMasterTemplate(false);
    }

    /**
     * Gán cặp tên=>giá trị cho view
     * @param string $name
     * @param string $value
     */
    function assign($name, $value = "", $master = false)
    {
        if (!$master) {
            $this->_template->assign($name, $value);
        } else {
            $this->_master_template->assign($name, $value);
        }
    }

    public function render()
    {

        # Get sub template filename
        $sub_temp_file = VIEWS_DIR . $this->_controller . DS . $this->_action . '.tpl';
        # if don't use wrapper or is an ajax request then response json data


        if (App::isAjaxRequest()) {
            echo $this->_template->json();
        } elseif ($this->_use_master_template) {

            $this->_master_template->assign('sub_template',
                $this->_template->render($sub_temp_file, Loader::getConfig('app', 'template_cache')));

            $this->_master_template_file === FALSE &&
                $this->_master_template_file = Loader::getConfig('app', 'default_master_template');

            $this->_master_template->preCompile(VIEWS_DIR . $this->_master_template_file);

            foreach ($this->_template->getCss() as $css) {
                $this->_master_template->css($css['file'], $css['media']);
            }

            foreach ($this->_template->getJs() as $js) {
                $this->_master_template->js($js);
            }

            $this->_master_template->display();

        } else {
            $this->_template->display($sub_temp_file);
        }
    }
}